package com.smartlazy.delay.queue.core.service;

import com.alibaba.fastjson.JSONObject;
import com.smartlazy.delay.queue.core.bean.JobItem;
import com.smartlazy.delay.queue.core.constant.CommonConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;

/**
 *
 * @author howe
 */
@Slf4j
@Service
public class DelayJob implements Serializable {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 获取Job
     * @param jobId
     */
    public JobItem getJob(String jobId) {
        String key = CommonConst.DEFAULT_JOB_KEY + jobId;
        ValueOperations<String, String> vo = redisTemplate.opsForValue();
        String jobStr = vo.get(key);
        JobItem ret = JSONObject.parseObject(jobStr, JobItem.class);
        return ret;
    }

    /**
     * 添加Job
     * @param jobId
     * @param job
     */
    public void putJob(String jobId, JobItem job) {
        String key = CommonConst.DEFAULT_JOB_KEY + jobId;
        ValueOperations<String, String> vo = redisTemplate.opsForValue();
        vo.set(key, JSONObject.toJSONString(job));
    }

    /**
     * 删除Job
     * @param jobId
     */
    public Boolean removeJob(String jobId) {
        String key = CommonConst.DEFAULT_JOB_KEY + jobId;
        return redisTemplate.delete(key);
    }
}
